const wxPaymentApi = require('../weixin/payment');
const OrderStatus = require('../../module/const/OrderStatus');
const Order = require('../../entity/product/order');
const { generateRandomUUID } = require('../../module/tool/common');
const timeTool = require('../../module/tool/time');

const orderNotifyUrl = '/payment/ordernotify';
const orderRefundNotifyUrl = '/payment/#orderId/#refundId/orderrefundnotify';

// 下单
async function makeMchBill (orderId, openid, price) {
    orderId = orderId.toString();
    let notifyUrl = wxPaymentApi.getPaymentNotifyHost() + orderNotifyUrl;
    console.log('下单：' + openid + ',' + notifyUrl);
    return wxPaymentApi.makeMehBill(orderId, orderId, price, openid, '大力蛮牛商品下单', notifyUrl);
}

// 下单回调
async function orderPaymentNotify (notifyData) {
    let xmlBuilder = wxPaymentApi.getXmlTool()[0];
    if (notifyData.xml.result_code === 'SUCCESS') {
        let orderId = notifyData.xml.attach;
        // 更改订单状态为已付款
        const OrderModel = new Order().getModel();
        const orderData = await OrderModel.findById(orderId);

        if (orderData.status === OrderStatus.Committed.value) {
            // 支付成功
            orderData.status = OrderStatus.Payed.value;
            orderData.payTime = timeTool.getCurrentTimestamp();
            orderData.save();
        }
    }
    console.log('微信支付回调成功：' + notifyData.xml.attach);
    return xmlBuilder.buildObject({
        return_code: 'SUCCESS',
        return_msg: 'OK'
    });
}

// 退款
async function orderRefund (price, orderId, refundDesc) {
    let refundId = generateRandomUUID();
    let refundNotifyUrl = wxPaymentApi.getPaymentNotifyHost() + orderRefundNotifyUrl.replace('#orderId', orderId).replace('#refundId', refundId);
    console.log('退款：' + orderId + ',' + refundId);
    return wxPaymentApi.orderRefund(refundId, orderId, price, refundDesc, refundNotifyUrl);
}

// 退款回调
async function orderRefundNotify (orderId, refundId, notifyData) {
    let xmlBuilder = wxPaymentApi.getXmlTool()[0];
    console.log('退款成功：' + orderId + ',' + refundId);
    return xmlBuilder.buildObject({
        return_code: 'SUCCESS',
        return_msg: 'OK'
    });
}

// 查询订单详情
async function orderHasPayed (orderId) {
    return wxPaymentApi.orderHasPayed(orderId);
}

module.exports = {
    makeMchBill,
    orderPaymentNotify,
    orderRefund,
    orderRefundNotify,
    orderHasPayed
};
